import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { gql, useQuery, useMutation } from '@apollo/client';

import Button from '@kuiper-components/button';
import Loading from '@kuiper-components/loading';
import { withRouter } from 'react-router';

import s from './style.module.css';
import { datetime } from '../../../../common/formatter';
import confirm from '../../../components/confirm';

const USER_QUERY = gql`
	{
		UserOne {
			_id
			disclaimerAgreeTime
		}
	}
`;

const AGREE_DISCLAIMER = gql`
	mutation {
		UpdateAgreeTime {
			_id
			disclaimerAgreeTime
		}
	}
`;

function AgreePanel({ className, uid, history }) {
	const [updateAgreeDate] = useMutation(AGREE_DISCLAIMER);
	const { data, loading } = useQuery(USER_QUERY, {
		variables: { uid },
	});

	if (loading) return <Loading />;

	const agreeDate = data?.UserOne?.disclaimerAgreeTime;

	const handleAgree = () => {
		updateAgreeDate().then(({ data }) => {
			const agreeDate = data?.UpdateAgreeTime?.disclaimerAgreeTime || '';
			confirm.success({
				message: ` 您已于${datetime(
					agreeDate,
					'yyyy年MM月dd日'
				)}同意《知道创宇ScanV监测服务条款》。`,
				okText: '添加资产',
				cancelText: '取消',
				onOk: () => {
					history.push('/jobs');
				},
			});
		});
	};

	return (
		<div className={cn(className, s.agreePanel, { [s.center]: !agreeDate })}>
			{agreeDate ? (
				<span>同意时间：{datetime(agreeDate, 'yyyy年MM月dd日')}</span>
			) : (
				<Button className={className} primary onClick={handleAgree}>
					已阅读并同意
				</Button>
			)}
		</div>
	);
}

AgreePanel.propTypes = {
	className: PropTypes.string,
	uid: PropTypes.string.isRequired,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
	}),
};
AgreePanel.defaultProps = {
	className: '',
};

export default withRouter(AgreePanel);
